package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;
    @Override
    public List<Map> findMenuByUsername(String username) {
         List<Menu> menus =menuDao.findMenuByUsername(username);
         List<Map> res = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentMenuId()==null) {
                Map map = new HashMap();
                map.put("path", menu.getPath());
                map.put("title", menu.getName());
                map.put("icon", menu.getIcon());
                map.put("children", getMenuChildren(menus, menu.getId()));
                res.add(map);
            }
        }
        return res;
    }

    private List<Map> getMenuChildren(List<Menu> menus, Integer id) {
        List<Map> children = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentMenuId()==id){
                Map map = new HashMap();
                map.put("path",menu.getPath());
                map.put("title",menu.getName());
                map.put("linkUrl",menu.getLinkUrl());
                children.add(map);
            }
        }
        return children;
    }
}
